/**
 * @Description: 其余git工具命令
 * @author Beon
 * @date 2021/1/14
*/
import * as childProcess from 'child_process';
import {OtherInquirer} from '../inquirer/otherInquirer';
import {ErrorCatch} from '../decorators/errorCatch';

export class BranchOrigin{
    static gitBranch: string
    static gitOrigin: string[]
    static Origins: string[]

    /**
     * 获取当前分支git
     * @returns {Promise<string>}
     */
    @ErrorCatch.errorExit('获取当前分支失败')
    static async getBranch(repoPath?: string): Promise<string> {
        const allBranch = await childProcess.execSync('git branch', { cwd: repoPath }).toString().trim(); // 获取分支信息
        return allBranch.split('\n').filter((item) => item[0] === '*')[0].substring(2);
    }

    /**
     * 获取当前remote
     * @returns {Promise<string>}
     */
    @ErrorCatch.errorExit('获取当前remote失败')
    static async getRemote(repoPath?: string): Promise<string[]> {
        const remote = await childProcess.execSync('git remote', { cwd: repoPath }).toString().trim(); // 获取分支信息
        return remote.split('\n');
    }

    /**
     * 获取当前远端库详细信息
     * @returns {Promise<string>}
     */
    @ErrorCatch.errorExit('获取当前远端库详情失败')
    static async getRemoteV(repoPath?: string): Promise<string[]> {
        const remote = await childProcess.execSync('git remote -v', { cwd: repoPath }).toString().trim(); // 获取分支信息
        return remote.split('\n');
    }

    /**
     * 处理分支参数
     * @param repoPath
     * @returns {Promise<void>}
     */
    static async dealBranchMessage(repoPath?: string): Promise<void> {
        this.gitBranch = await this.getBranch(repoPath);
    }

    /**
     * 处理远端库参数
     * @param repoPath
     * @returns {Promise<void>}
     */
    static async dealOriginMessage(repoPath?: string): Promise<void> {
        const getOrigin = await this.getRemote(repoPath);
        this.gitOrigin = getOrigin[1] ? await OtherInquirer.checkboxInquirerFn(getOrigin) : getOrigin;
    }

    /**
     * 处理远端库url参数
     * @param repoPath
     * @returns {Promise<void>}
     */
    static async dealOriginUrlMessage(repoPath?: string): Promise<void> {
        const regUrl = /http[^\s]*/;
        const regName = /[^\t]*/;
        const originList = await this.getRemoteV(repoPath);
        let originObj = originList.reduce((obj, item) => {
            obj[item.match(regName)[0]] = item.match(regUrl)[0];
            return obj;
        }, {});

        this.Origins = Object.keys(originObj).length > 1
            ? (await OtherInquirer.checkboxInquirerFn(Object.keys(originObj))).map((item) => originObj[item])
            : Object.values(originObj);
    }
}
